package com.application.viewmodel;

import android.app.Application;
import android.widget.Toast;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import com.application.RetrofitInterface;
import com.application.RetrofitRxJavaClient;
import com.application.User;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.jetbrains.annotations.NotNull;

public class RetrofitRxJavaViewModel extends AndroidViewModel {
    public final MutableLiveData<String> requestResult = new MutableLiveData<>("");
    private Disposable requestDisposable;

    public RetrofitRxJavaViewModel(Application application) {
        super(application);
    }

    public void startRxJavaRequest() {
        RetrofitInterface apiService = RetrofitRxJavaClient.getInstance().getApiService();
        if (requestDisposable != null && !requestDisposable.isDisposed()) {
            requestDisposable.dispose();
        }
        requestDisposable = apiService.getUserByJava(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        this::handleRequestSuccess,
                        this::handleRequestError
                );
    }

    private void handleRequestSuccess(User user) {
        String result = "用户ID:" + user.getId() + "\n" +
                "用户名:" + user.getUsername() + "\n" +
                "邮箱:" + user.getEmail() + "\n";
        requestResult.setValue(result);
    }

    private void handleRequestError(Throwable throwable) {
        String errorMsg = "请求失败：" + throwable.getMessage();
        requestResult.setValue(errorMsg);
        Toast.makeText(getApplication(), "获取用户信息失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (requestDisposable != null && !requestDisposable.isDisposed()) {
            requestDisposable.dispose();
        }
    }
}
